Exercise 4

Work summary

Codes are available at

Data load and description

Boston dataset contains information collected by the U.S Census Service concerning housing valuesin the area of Boston Mass. It was obtained from the StatLib archive. More information about each variable can be found in here

Descriptions of variables are:

  • CRIM: Per capita crime rate by town
  • ZN Proportion of residential land zoned for lots over 25,000 sq. ft
  • INDUS: Proportion of non-retail business acres per town
  • CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
  • NOX: Nitric oxide concentration (parts per 10 million)
  • RM: Average number of rooms per dwelling
  • AGE: Proportion of owner-occupied units built prior to 1940
  • DIS: Weighted distances to five Boston employment centers
  • RAD: Index of accessibility to radial highways
  • TAX: Full-value property tax rate per $10,000
  • PTRATIO: Pupil-teacher ratio by town
  • B: 1000(Bk — 0.63)², where Bk is the proportion of [people of African American descent] by town
  • LSTAT: Percentage of lower status of the population
  • MEDV: Median value of owner-occupied homes in $1000s
library(MASS)
data("Boston")
dim(Boston)
## [1] 506  14
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

According to the information the Boston data frame has 506 rows and 14 columns. That is equal to my check. All variables are either numeric or int. There is no missing values either:

sum(is.na(Boston))
## [1] 0
mean(is.na(Boston))
## [1] 0

From graphical overview it is easy to notice at least the following:

  • rm & medv, nox & indus, age & nox, tax & indus have positive correlation
  • dis & indus, dis & nox, dis & age, lstat & medv have negative correation
  • medv and rm seem to fit linear distribution
  • age and black are left-tailed
  • crim, dis are right-tailed
  • tax, rad and indus are bimodally distributed
  • lstat, nox and dis are skewed to the left
  • variable chas seems a little odd. However,Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) can be only 0 or 1 and therefore it is different from other variables.
library(GGally)
library(ggplot2)

ggpairs(Boston, title=“Scatter plot matrix, distributions”,lower = list( continuous = “smooth”,mapping = aes()))

Scatter plot matrix

Scatter plot matrix

pairs(Boston[-1], main="Graphical summary")

Standardization and crime rate variable

Scaling targets to normalising:

boston_scaled <- scale(Boston)
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865

When summary of scaled data is compared to the summary of the original data, it is obvious that magnitudes of min and max values have decreased and mean is always 0. For instance, max of lstat was 37.97 and after scaling 3.54, respectively black max 396.9 and 0.44. Zn min was 0, now -0.49, rm min was 3.56, now -3.88.

Next, categorial variable crim and its quantiles are calculated:

# change the object to data frame, because vector otherwise causes an error in next phase
boston_scaled<-as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

Testing and training sets are created:

# number of rows in the Boston dataset 
n <- nrow(boston_scaled)
# randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)
# creating train set
train <- boston_scaled[ind,]
# create testing set 
test <- boston_scaled[-ind,]
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)

LDA

Classification method LDA is used to findthe variables that separate the classes best and predict the classes of new data. In order to work, the variables should be normally distributed and each variable should have the same variance. Therefore scaled boston data is used. LDA model is created below and Crime is the target variable.

lda.fit <- lda(crime~., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2574257 0.2400990 0.2475248 0.2549505 
## 
## Group means:
##                   zn      indus         chas        nox         rm
## low       0.94234126 -0.9141363 -0.158758869 -0.8665957  0.4762828
## med_low  -0.09515751 -0.2648079 -0.069385757 -0.5613385 -0.1391196
## med_high -0.39119540  0.2206186  0.239493963  0.3782000  0.1066094
## high     -0.48724019  1.0170891 -0.004759149  1.0401334 -0.3749690
##                 age        dis        rad        tax     ptratio
## low      -0.9035376  0.8268395 -0.6803986 -0.7292769 -0.51109606
## med_low  -0.3760440  0.3506590 -0.5497161 -0.4782821 -0.05279416
## med_high  0.4460251 -0.3577082 -0.4317555 -0.3176579 -0.23720393
## high      0.8201146 -0.8548452  1.6384176  1.5142626  0.78111358
##                black       lstat        medv
## low       0.38361231 -0.79055067  0.56130560
## med_low   0.30878522 -0.15355818 -0.03371995
## med_high  0.06306563  0.02997268  0.11657949
## high     -0.78303889  0.90850827 -0.66133000
## 
## Coefficients of linear discriminants:
##                  LD1         LD2         LD3
## zn       0.093836889  0.66816908 -0.85348076
## indus    0.089393496 -0.35651311  0.41121469
## chas    -0.100464416 -0.10866675  0.07549712
## nox      0.362558837 -0.65953916 -1.26756275
## rm      -0.109952100 -0.12341475 -0.17430803
## age      0.247125358 -0.45721776 -0.24572262
## dis     -0.038049649 -0.40423112  0.14937313
## rad      3.441734203  0.93138090 -0.06629934
## tax     -0.003899325  0.03794687  0.43861076
## ptratio  0.116295938 -0.02679021 -0.19427459
## black   -0.092407423  0.02282013  0.11411675
## lstat    0.250246782 -0.21983391  0.31088939
## medv     0.213213938 -0.33876577 -0.23633272
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9554 0.0343 0.0102
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)

Prior probabilities tell how training observations fell to crime categories. All probabilities are around 25 %. Group means show the mean value of each group by each variable. Coefficients of linear discriminants provides the linear combinations that are used to form the LDA decision rule. For instance, 0.131033364 * zn + 0.047138924 * indus ….0.237478243 * medv is the rule for LD1. Index of accessibility to radial highways (rad) has the largest coefficient value meaning it contibutes most. Average number of rooms per dwelling (rm) has the smallest coefficient; bigger houses with more rooms tend to locate on areas of low crime rates.Fit between proportion of trace fit between group variants

Proportion of trace is the percentage separation that each of the discriminant achieves. LD1 achieves already 95 %, when LD2 and LD 3 have only 4 % and 1 %. This means that the first linear discrimination is already enough.

There is a LDA biplot below.The biplot visualizes how variable rad contributes a lot in LD1 and it is contributing a lot also in LD2. Variable nox contributes in LD1 positively and in LD2 negatively, which was also seen from coefficients. Zn contributes in LD2, but not much in LD1. Other variables are around zero and do not stand out.

# plot the lda results
plot(lda.fit, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit, myscale = 1)

lda.pred <- predict(lda.fit, newdata = test)

Next correct classes are saved and categorical variable is removed: correct_classes <- test$crime test <- dplyr::select(test, -crime)

Crime categories are cross tabulated by correct and predicted values. High values are well predicted. Lowest values were well predicted as well. Low med and high med categories have more incorrect predictions, but also for them most predictions went right.

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       15       7        1    0
##   med_low    5      14       10    0
##   med_high   1       5       18    2
##   high       0       0        0   24

Distances and kmeans

Boston dataset is reloaded again and the done modifications are not valid any more. Data is standardized by using scale function. Scaling was successfull, means are 0.

library(MASS)
data("Boston")
boston_scaled2 <- scale(Boston)
summary(boston_scaled2)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
class(boston_scaled2)
## [1] "matrix"
boston_scaled2<-as.data.frame(boston_scaled2)

Distances calculation:

dist_eu<- dist(boston_scaled2)
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970

Kmeans clustering and pairs are calculated, but the number of centers here is 4, which is just a guess what could be the optimal number.

km4 <-kmeans(boston_scaled2, centers = 4)
pairs(boston_scaled2, col = km4$cluster)

str(km4)
## List of 9
##  $ cluster     : Named int [1:506] 4 4 4 4 4 4 4 4 2 4 ...
##   ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
##  $ centers     : num [1:4, 1:14] 1.063 -0.325 -0.414 -0.393 -0.487 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:4] "1" "2" "3" "4"
##   .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
##  $ totss       : num 7070
##  $ withinss    : num [1:4] 1198 837 305 1148
##  $ tot.withinss: num 3488
##  $ betweenss   : num 3582
##  $ size        : int [1:4] 132 116 65 193
##  $ iter        : int 3
##  $ ifault      : int 0
##  - attr(*, "class")= chr "kmeans"
km4
## K-means clustering with 4 clusters of sizes 132, 116, 65, 193
## 
## Cluster means:
##         crim         zn      indus         chas        nox         rm
## 1  1.0632703 -0.4872402  1.0149946 -0.033716932  1.0159127 -0.3735788
## 2 -0.3250693 -0.4826198  0.5605091  0.168897683  0.4463218 -0.5729391
## 3 -0.4135478  2.2539281 -1.1502450 -0.211758295 -1.1815084  0.6543177
## 4 -0.3925546 -0.1357810 -0.6436913 -0.007135788 -0.5651594  0.3794958
##          age        dis        rad        tax     ptratio       black
## 1  0.7542188 -0.8233749  1.6596029  1.5294129  0.80577843 -0.75124560
## 2  0.6634100 -0.5376344 -0.5907984 -0.2264164  0.08504675  0.05506337
## 3 -1.4746155  1.6280013 -0.6585336 -0.5368747 -0.79454608  0.34634486
## 4 -0.4179401  0.3379844 -0.5581880 -0.7291262 -0.33462529  0.36406556
##        lstat       medv
## 1  0.8328654 -0.6664074
## 2  0.5518771 -0.4617322
## 3 -0.9492429  0.7282687
## 4 -0.5816331  0.4880272
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   4   4   4   4   4   4   4   4   2   4   4   4   4   4   2   4   4   2 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   4   2   2   2   2   2   2   2   2   2   2   4   2   2   2   2   2   4 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   4   4   4   3   3   4   4   4   4   4   4   4   2   4   4   4   4   4 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   3   3   3   3   4   4   4   4   4   4   4   3   3   4   4   4   4   4 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   4   4   4   4   4   4   4   4   4   4   4   4   4   4   4   4   4   4 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   4   4   4   4   4   4   4   4   4   4   4   4   2   2   2   2   2   2 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   2   2   4   4   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   4   2   2   2   4 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   4   4   2   2   4   2   2   2   2   2   2   4   4   4   4   4   4   4 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   4   4   4   4   4   4   4   3   3   3   3   3   3   3   3   3   3   3 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   3   3   3   3   3   3   3   4   4   2   4   2   2   2   2   4   2   4 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   2   4   2   2   4   2   4   4   4   4   4   4   4   4   4   4   4   4 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   4   4   4   4   3   4   4   4   4   3   4   4   4   4   4   3   3   3 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   3   3   3   3   3   4   4   4   4   4   4   4   4   4   4   4   4   4 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   4   4   4   4   4   4   4   4   4   4   4   4   4   3   3   3   3   3 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   3   3   3   3   3   4   4   4   4   4   3   3   3   4   3   3   4   4 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   4   4   4   2   2   4   2   4   4   2   2   2   4   4   4   4   4   4 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   4   4   4   4   4   4   4   3   3   4   4   4   4   4   4   4   4   3 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   4   3   3   4   4   3   3   3   3   3   3   3   3   3   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   1   1   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   4 
## 505 506 
##   2   2 
## 
## Within cluster sum of squares by cluster:
## [1] 1198.3572  836.7043  305.1560 1147.7552
##  (between_SS / total_SS =  50.7 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"

Finding the optimal number of clusters is not irrelevant question and the textbook recommends the method to plot within-group sum of squares associated with the k-means solution for each number of groups. Then the “elbow” in the picture gives indication of the most useful solution. The plot below indicates that the elbow is in 2, after 2 the decrease is slower. However, even with 3 it is still significant but I choose to use 2.

set.seed(123)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line', main="WGSS and groups in K-means solution")

Only 51 % total variance in data set that is explained by the first clustering with 4 clusters, which is not impressive. I checked how many clusters I should have to gain 80 % of total variance and it was 20. It is clear that it is too much, so I still keep 2 clusters, although the biggest decrease of variation ends at 2. In real-life I should check the correct number of clusters also by other methods, e.g. silhouette.

km <-kmeans(boston_scaled2, centers = 2)
pairs(boston_scaled2, col = km$cluster)

Cluster visualization with 2 clusters is clearer than the first guess of 4.

str(km)
## List of 9
##  $ cluster     : Named int [1:506] 1 1 1 1 1 1 1 1 1 1 ...
##   ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
##  $ centers     : num [1:2, 1:14] -0.389 0.724 0.262 -0.487 -0.615 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "1" "2"
##   .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
##  $ totss       : num 7070
##  $ withinss    : num [1:2] 2686 1891
##  $ tot.withinss: num 4577
##  $ betweenss   : num 2493
##  $ size        : int [1:2] 329 177
##  $ iter        : int 1
##  $ ifault      : int 0
##  - attr(*, "class")= chr "kmeans"
km
## K-means clustering with 2 clusters of sizes 329, 177
## 
## Cluster means:
##         crim         zn      indus         chas        nox         rm
## 1 -0.3894158  0.2621323 -0.6146857  0.002908943 -0.5823397  0.2446705
## 2  0.7238295 -0.4872402  1.1425514 -0.005407018  1.0824279 -0.4547830
##          age        dis        rad        tax    ptratio      black
## 1 -0.4331555  0.4540421 -0.5828749 -0.6291043 -0.2943707  0.3282754
## 2  0.8051309 -0.8439539  1.0834228  1.1693521  0.5471636 -0.6101842
##        lstat       medv
## 1 -0.4530491  0.3532917
## 2  0.8421083 -0.6566834
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   1   1   1 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   2   1 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   1   1   2   1   1 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   2   1   2   1   1   2   2   1   1   1   1   1   1   1   1 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 505 506 
##   1   1 
## 
## Within cluster sum of squares by cluster:
## [1] 2686.045 1890.637
##  (between_SS / total_SS =  35.3 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"

The plot picture shows the groups are not equal size, one is 177 and other 329. There are some pairs, in which the grouping seems to work nicely; for instance medvd & lstat, lstat & nox,dis & nox and rm & nox. But for some pairs the groups are unclear, for instance rm&ptratio, age & ptratio, ptratio & lstat.

km <-kmeans(boston_scaled2, centers = 2)
str(km)
## List of 9
##  $ cluster     : Named int [1:506] 2 2 2 2 2 2 2 2 2 2 ...
##   ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
##  $ centers     : num [1:2, 1:14] 0.724 -0.389 -0.487 0.262 1.143 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "1" "2"
##   .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
##  $ totss       : num 7070
##  $ withinss    : num [1:2] 1891 2686
##  $ tot.withinss: num 4577
##  $ betweenss   : num 2493
##  $ size        : int [1:2] 177 329
##  $ iter        : int 1
##  $ ifault      : int 0
##  - attr(*, "class")= chr "kmeans"

Bonus: K-means and LDA fitting

Start again with data reloading and scaling

library(MASS)
library(ggplot2)
library(tidyr)
library(cluster)
data("Boston")
boston_scaled3 <- scale(Boston)
boston_scaled3<-as.data.frame(boston_scaled3)

Number of clusters is selected to be 5 and clusters are target classess.

km_4 <-kmeans(boston_scaled3, centers = 5)
lda.fit2 <- lda(km_4$cluster ~., data = boston_scaled3)
lda.fit2
## Call:
## lda(km_4$cluster ~ ., data = boston_scaled3)
## 
## Prior probabilities of groups:
##          1          2          3          4          5 
## 0.25296443 0.21146245 0.31027668 0.09881423 0.12648221 
## 
## Group means:
##         crim         zn      indus       chas        nox         rm
## 1  1.0878724 -0.4872402  1.0149946 -0.1492947  1.0187219 -0.4210063
## 2 -0.3243708 -0.4822312  0.6185681  0.1324196  0.4947716 -0.5346882
## 3 -0.3981592 -0.1664810 -0.6090235 -0.2221749 -0.6655615 -0.1199301
## 4 -0.3103881 -0.1159242 -0.4991257  1.0662850 -0.0692028  1.6606848
## 5 -0.4142124  2.2796750 -1.1802049 -0.2108119 -1.1778698  0.7327381
##          age        dis        rad        tax    ptratio      black
## 1  0.7521154 -0.8135370  1.6596029  1.5294129  0.8057784 -0.7784115
## 2  0.7503783 -0.5640394 -0.5954711 -0.1985406  0.1042866  0.0419631
## 3 -0.6336330  0.5362710 -0.5817365 -0.7039306 -0.0756665  0.3655348
## 4  0.2630692 -0.4217934 -0.3042757 -0.5487050 -0.9864145  0.3028535
## 5 -1.4099114  1.5840638 -0.6588648 -0.5713854 -0.8296553  0.3533591
##        lstat        medv
## 1  0.8914421 -0.75669132
## 2  0.5669361 -0.49061591
## 3 -0.4149421  0.05516096
## 4 -0.9553010  1.76459824
## 5 -0.9664968  0.81972201
## 
## Coefficients of linear discriminants:
##                  LD1          LD2         LD3         LD4
## crim    -0.053751141  0.179074873  0.13780108 -0.07519738
## zn       0.062843967  1.465907935 -0.50908589  1.32076958
## indus   -0.179836757 -0.391770295 -0.40486479  0.39138090
## chas     0.230845551 -0.111364285  0.41752818  0.17516588
## nox      0.076978215 -0.081264681 -0.04255968  0.44218751
## rm      -0.111320904  0.164332062  0.59726088  0.22808090
## age     -0.048463133 -0.522072143  0.34421689  0.63414099
## dis      0.291886353  0.306401440 -0.21018069 -0.27013447
## rad     -4.160201638  1.135383393  0.44562029 -1.62967439
## tax      0.204066630  0.381083248 -0.11925476  1.00108406
## ptratio  0.009872979 -0.170859777 -0.22250511  0.33481849
## black    0.025657288  0.005723222 -0.01480980 -0.08944504
## lstat   -0.105055816 -0.045731798  0.14150418  0.39609928
## medv     0.351343258  0.268482029  0.88984740  0.30142226
## 
## Proportion of trace:
##    LD1    LD2    LD3    LD4 
## 0.7423 0.1680 0.0517 0.0381
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

Biplot drawing next:

plot(lda.fit2, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit2, myscale = 1)

Everytime the model is run again, the results change. But rad and zn are standing out, also chas every so often. Arrows for each variable point in the direction of increasing values of that variable.Rad increases meaning higher the value, the more meaningful it is in clustering where it is pointin. Otherwise all variables are around zero meaning they are not influencial

3D Bonus

I copied the lines from the instructions and did the package installation

model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

Then I tried plotting as instucted

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')

However, at this point I run into trouble with WebGL. In the help page the cube is rolling but I just did not succeed in R Studio.

Data wrangling for exercise 5

hd <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human_development.csv", stringsAsFactors = F)
gii <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/gender_inequality.csv", stringsAsFactors = F, na.strings = "..")
#checking the dimension
dim(hd)
## [1] 195   8
dim(gii)
## [1] 195  10
#checking the structure
str(hd)
## 'data.frame':    195 obs. of  8 variables:
##  $ HDI.Rank                              : int  1 2 3 4 5 6 6 8 9 9 ...
##  $ Country                               : chr  "Norway" "Australia" "Switzerland" "Denmark" ...
##  $ Human.Development.Index..HDI.         : num  0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
##  $ Life.Expectancy.at.Birth              : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ Expected.Years.of.Education           : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ Mean.Years.of.Education               : num  12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
##  $ Gross.National.Income..GNI..per.Capita: chr  "64,992" "42,261" "56,431" "44,025" ...
##  $ GNI.per.Capita.Rank.Minus.HDI.Rank    : int  5 17 6 11 9 11 16 3 11 23 ...
str(gii)
## 'data.frame':    195 obs. of  10 variables:
##  $ GII.Rank                                    : int  1 2 3 4 5 6 6 8 9 9 ...
##  $ Country                                     : chr  "Norway" "Australia" "Switzerland" "Denmark" ...
##  $ Gender.Inequality.Index..GII.               : num  0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
##  $ Maternal.Mortality.Ratio                    : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ Adolescent.Birth.Rate                       : num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ Percent.Representation.in.Parliament        : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
##  $ Population.with.Secondary.Education..Female.: num  97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
##  $ Population.with.Secondary.Education..Male.  : num  96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
##  $ Labour.Force.Participation.Rate..Female.    : num  61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
##  $ Labour.Force.Participation.Rate..Male.      : num  68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
summary(hd)
##     HDI.Rank        Country          Human.Development.Index..HDI.
##  Min.   :  1.00   Length:195         Min.   :0.3480               
##  1st Qu.: 47.75   Class :character   1st Qu.:0.5770               
##  Median : 94.00   Mode  :character   Median :0.7210               
##  Mean   : 94.31                      Mean   :0.6918               
##  3rd Qu.:141.25                      3rd Qu.:0.8000               
##  Max.   :188.00                      Max.   :0.9440               
##  NA's   :7                                                        
##  Life.Expectancy.at.Birth Expected.Years.of.Education
##  Min.   :49.00            Min.   : 4.10              
##  1st Qu.:65.75            1st Qu.:11.10              
##  Median :73.10            Median :13.10              
##  Mean   :71.07            Mean   :12.86              
##  3rd Qu.:76.80            3rd Qu.:14.90              
##  Max.   :84.00            Max.   :20.20              
##                                                      
##  Mean.Years.of.Education Gross.National.Income..GNI..per.Capita
##  Min.   : 1.400          Length:195                            
##  1st Qu.: 5.550          Class :character                      
##  Median : 8.400          Mode  :character                      
##  Mean   : 8.079                                                
##  3rd Qu.:10.600                                                
##  Max.   :13.100                                                
##                                                                
##  GNI.per.Capita.Rank.Minus.HDI.Rank
##  Min.   :-84.0000                  
##  1st Qu.: -9.0000                  
##  Median :  1.5000                  
##  Mean   :  0.1862                  
##  3rd Qu.: 11.0000                  
##  Max.   : 47.0000                  
##  NA's   :7
summary(gii)
##     GII.Rank        Country          Gender.Inequality.Index..GII.
##  Min.   :  1.00   Length:195         Min.   :0.0160               
##  1st Qu.: 47.75   Class :character   1st Qu.:0.2030               
##  Median : 94.00   Mode  :character   Median :0.3935               
##  Mean   : 94.31                      Mean   :0.3695               
##  3rd Qu.:141.25                      3rd Qu.:0.5272               
##  Max.   :188.00                      Max.   :0.7440               
##  NA's   :7                           NA's   :33                   
##  Maternal.Mortality.Ratio Adolescent.Birth.Rate
##  Min.   :   1.0           Min.   :  0.60       
##  1st Qu.:  16.0           1st Qu.: 15.45       
##  Median :  69.0           Median : 40.95       
##  Mean   : 163.2           Mean   : 49.55       
##  3rd Qu.: 230.0           3rd Qu.: 71.78       
##  Max.   :1100.0           Max.   :204.80       
##  NA's   :10               NA's   :5            
##  Percent.Representation.in.Parliament
##  Min.   : 0.00                       
##  1st Qu.:12.47                       
##  Median :19.50                       
##  Mean   :20.60                       
##  3rd Qu.:27.02                       
##  Max.   :57.50                       
##  NA's   :3                           
##  Population.with.Secondary.Education..Female.
##  Min.   :  0.9                               
##  1st Qu.: 27.8                               
##  Median : 55.7                               
##  Mean   : 54.8                               
##  3rd Qu.: 81.8                               
##  Max.   :100.0                               
##  NA's   :26                                  
##  Population.with.Secondary.Education..Male.
##  Min.   :  3.20                            
##  1st Qu.: 38.30                            
##  Median : 60.00                            
##  Mean   : 60.29                            
##  3rd Qu.: 85.80                            
##  Max.   :100.00                            
##  NA's   :26                                
##  Labour.Force.Participation.Rate..Female.
##  Min.   :13.50                           
##  1st Qu.:44.50                           
##  Median :53.30                           
##  Mean   :52.61                           
##  3rd Qu.:62.62                           
##  Max.   :88.10                           
##  NA's   :11                              
##  Labour.Force.Participation.Rate..Male.
##  Min.   :44.20                         
##  1st Qu.:68.88                         
##  Median :75.55                         
##  Mean   :74.74                         
##  3rd Qu.:80.15                         
##  Max.   :95.50                         
##  NA's   :11

Renaming the columns:

names(hd)[names(hd) == "Human.Development.Index..HDI."] <- "HDI"
names(hd)[names(hd) == "Expected.Years.of.Education"] <- "EYE"
names(hd)[names(hd) == "Life.Expectancy.at.Birth"] <- "LEB"
names(hd)[names(hd) == "Mean.Years.of.Education"] <- "MYE"
names(hd)[names(hd) == "Gender.Inequality.Index..GII."] <- "GII"
names(hd)[names(hd) == "Maternal.Mortality.Ratio"] <- "MMR"
names(hd)[names(hd) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(hd)[names(hd) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(hd)[names(hd) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(hd)[names(hd) == "GNI.per.Capita.Rank.Minus.HDI.Rank"] <- "GNIMinusHDIRank"
names(gii)[names(gii) == "Adolescent.Birth.Rate"] <- "ADBR"
names(gii)[names(gii) == "Expected.Years.of.Education"] <- "EYE"
names(gii)[names(gii) == "Life.Expectancy.at.Birth"] <- "LEB"
names(gii)[names(gii) == "Mean.Years.of.Education"] <- "MYE"
names(gii)[names(gii) == "Gender.Inequality.Index..GII."] <- "GII"
names(gii)[names(gii) == "Maternal.Mortality.Ratio"] <- "MMR"
names(gii)[names(gii) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(gii)[names(gii) == "Population.with.Secondary.Education..Male."] <- "SecEducMale"
names(gii)[names(gii) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(gii)[names(gii) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Female."] <- "LabForParFem"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Male."] <- "LabForParMale"
head(hd)
##   HDI.Rank     Country   HDI  LEB  EYE  MYE GNIncPerCap GNIMinusHDIRank
## 1        1      Norway 0.944 81.6 17.5 12.6      64,992               5
## 2        2   Australia 0.935 82.4 20.2 13.0      42,261              17
## 3        3 Switzerland 0.930 83.0 15.8 12.8      56,431               6
## 4        4     Denmark 0.923 80.2 18.7 12.7      44,025              11
## 5        5 Netherlands 0.922 81.6 17.9 11.9      45,435               9
## 6        6     Germany 0.916 80.9 16.5 13.1      43,919              11
head(gii)
##   GII.Rank     Country   GII MMR ADBR PerParliament SecEducFemal
## 1        1      Norway 0.067   4  7.8          39.6         97.4
## 2        2   Australia 0.110   6 12.1          30.5         94.3
## 3        3 Switzerland 0.028   6  1.9          28.5         95.0
## 4        4     Denmark 0.048   5  5.1          38.0         95.5
## 5        5 Netherlands 0.062   6  6.2          36.9         87.7
## 6        6     Germany 0.041   7  3.8          36.9         96.3
##   SecEducMale LabForParFem LabForParMale
## 1        96.7         61.2          68.7
## 2        94.6         58.8          71.8
## 3        96.6         61.8          74.9
## 4        96.6         58.7          66.4
## 5        90.5         58.5          70.6
## 6        97.0         53.6          66.4